<template>
  <div v-loading="loading">
    <el-form ref="form" :model="form" :rules="rules" label-width="120px" class="dataForm">
      <el-row>
        <el-col :span="24">
          <el-form-item :label="$t('申请标题')" prop="actTitle">
            <el-input v-model="form.actTitle" :placeholder="$t('申请标题')" show-word-limit :maxlength="100" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('是否用印')" prop="isSeal">
            <el-radio-group v-model="form.isSeal">
              <el-radio
                v-for="dict in isSealOptions"
                :key="dict.dictValue"
                :label="dict.dictValue"
              >{{ $t(dict.dictLabel) }}</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('披露对象')" prop="disclosureObject">
            <el-select v-model="form.disclosureObject" :placeholder="$t('披露对象')">
              <el-option
                v-for="dict in disclosureObjectOptions"
                :key="dict.dictValue"
                :label="$t(dict.dictLabel)"
                :value="dict.dictValue"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('披露类型')" prop="disclosureType">
            <el-select v-model="form.disclosureType" :placeholder="$t('披露类型')">
              <el-option
                v-for="dict in disclosureTypeOptions"
                :key="dict.dictValue"
                :label="$t(dict.dictLabel)"
                :value="dict.dictValue"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('报告期-年')" prop="reportPeriodYear">
            <DatePicker
              v-model="form.reportPeriodYear"
              type="year"
              value-format="yyyy"
              :placeholder="$t('报告期-年')"
            />

          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('报告期-季')" prop="reportPeriodSeason">
            <el-select v-model="form.reportPeriodSeason" :placeholder="$t('报告期-季')">
              <el-option
                v-for="dict in reportPeriodSeasonOptions"
                :key="dict.dictValue"
                :label="$t(dict.dictLabel)"
                :value="dict.dictValue"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('报告类型')" prop="reportType">
            <el-select v-model="form.reportType" :placeholder="$t('报告类型')">
              <el-option
                v-for="(dict, index) in reportTypeOptions"
                :key="index"
                :value="dict.dictValue"
                :label="$t(dict.dictLabel)"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item :label="$t('备注')" prop="remark">
            <el-input v-model="form.remark" type="textarea" :placeholder="$t('备注')" show-word-limit :maxlength="2000" />
          </el-form-item>
        </el-col>
      </el-row>

      <!--用印明细-->
      <div v-if="form.isSeal === 'Y'" style="margin-top:8px;">
        <div class="area-header">
          <span class="area-header-title">{{ $t('用印明细') }}</span>
        </div>
        <el-table :data="form.oaSealDetailList" border class="nowrapTable formTable">
          <el-table-column :label="$t('序号')" align="center" width="50">
            <template slot-scope="scope">
              {{ scope.$index + 1 }}
            </template>
          </el-table-column>
          <el-table-column :label="$t('用印主体类型')" align="center" min-width="180">
            <template slot="header" slot-scope="{}">
              <i style="color: #ff4949;margin-right: 4px;">*</i>
              <span>{{ $t('用印主体类型') }}</span>
            </template>
            <template slot-scope="scope">
              <el-form-item :prop="'oaSealDetailList.' + scope.$index + '.investMainType'" :rules="oaSealDetailListRules.investMainType">
                <dictSelect
                  v-model="scope.row.investMainType"
                  :clearable="true"
                  dictionary="main_body_type"
                />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column :label="$t('用印主体')" align="center" min-width="350">
            <template slot="header" slot-scope="{}">
              <i style="color: #ff4949;margin-right: 4px;">*</i>
              <span>{{ $t('用印主体') }}</span>
            </template>
            <template slot-scope="scope">
              <el-form-item :prop="'oaSealDetailList.' + scope.$index + '.investMain'" :rules="oaSealDetailListRules.investMain">
                <MainBodySelect
                  v-model="scope.row.investMain"
                  :parameters="scope.row.investMainType"
                  @change="duplicateVerificationSubject"
                />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column :label="$t('用印类型')" align="center" min-width="300">
            <template slot="header" slot-scope="{}">
              <i style="color: #ff4949;margin-right: 4px;">*</i>
              <span>{{ $t('用印类型') }}</span>
            </template>
            <template slot-scope="scope">
              <el-form-item :prop="'oaSealDetailList.' + scope.$index + '.sealType'" :rules="oaSealDetailListRules.sealType">
                <el-select
                  v-model="scope.row.sealType"
                  multiple
                  :placeholder="$t('用印类型')"
                >
                  <el-option
                    v-for="dict in sealTypeDict"
                    :key="dict.dictValue"
                    :label="$t(dict.dictLabel)"
                    :value="dict.dictValue"
                  />
                </el-select>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column :label="$t('备注')" align="center" min-width="300">
            <template slot-scope="scope">
              <el-form-item :prop="'oaSealDetailList.' + scope.$index + '.remark'" :rules="oaSealDetailListRules.remark">
                <el-input v-model="scope.row.remark" type="textarea" :autosize="{ maxRows: 5 }" :maxlength="2000" show-word-limit :placeholder="$t('备注')" />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column v-if="!otherBtnHide" :label="$t('操作')" align="center" width="60px">
            <template slot-scope="scope">
              <el-button v-hasPermi="['fund:disclosure:remove']" type="text" icon="el-icon-delete" @click="delHandle(scope.$index, scope.row)" />
            </template>
          </el-table-column>
        </el-table>
        <div v-if="!otherBtnHide" class="tol">
          <el-button type="primary" icon="el-icon-plus" size="mini" @click="addPayment">{{ $t("添加") }}</el-button>
        </div>
      </div>
      <FileTable has-permi="fund:disclosure" :list.sync="form.fileList" data-type="fund_disclosure" :business-id="autoBusinessId($route.query.id, form)" :btn-show="!otherBtnHide" />
    </el-form>
    <div v-show="!btnHide" slot="footer" class="dialog-footer" style="text-align: right;">
      <!--保存，保存并启动流程，取消 三个按钮-->
      <FormBtn ref="formBtn" :bus-data="form" has-permi="fund:disclosure" :menu-key="menuKey" :btn-hide="btnHide" />
    </div>
  </div>
</template>

<script>
    import { saveFundDisclosure, getFundDisclosure } from '@/api/fund/disclosure/fundDisclosure'
    import { getFundName } from '@/api/fund/fundBase'
    import { deleteOaSealDetail } from '@/api/oa/seal/oaSeal'
    import MainBodySelect from '@/components/MainBodySelect'

    export default {
      components: {
        MainBodySelect
      },
        data() {
            return {
                // 是否隐藏其它按钮
                otherBtnHide: false,
                // 菜单标识
                menuKey: 'fund_disclosure',
                // 披露对象字典
                disclosureObjectOptions: [], // 披露类型字典
                disclosureTypeOptions: [], // 报告期-季字典
                reportPeriodSeasonOptions: [], // 表单参数
                reportTypeOptions: [], // 报告类型字典
                // 是否用印
                isSealOptions: [],
                // 用印类型
                sealTypeDict: [],
                form: {
                  fileList: []
                },
                // 表单校验
                rules: {
                disclosureObject: [
                  { required: true, message: this.$t('必填信息'), trigger: 'blur' }
                ], disclosureType: [
                  { required: true, message: this.$t('必填信息'), trigger: 'blur' }
                ], reportPeriodYear: [
                  { required: true, message: this.$t('必填信息'), trigger: 'blur' }
                ], reportPeriodSeason: [
                  { required: true, message: this.$t('必填信息'), trigger: 'blur' }
                ], actTitle: [
                  { required: true, message: this.$t('必填信息'), trigger: 'blur' }
                ], reportType: [
                  { required: true, message: this.$t('必填信息'), trigger: 'blur' }
                ], isSeal: [{ required: true, message: this.$t('必填信息'), trigger: 'blur' }]
                },
                oaSealDetailListRules: {
                  investMainType: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }],
                  investMain: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }],
                  sealType: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }]
                },
                // 遮罩层
                loading: false,
                // 操作按钮默认不展示
                buttonShow: true,
                // 是否隐藏保存等按钮
                btnHide: false
            }
        },
        created() {
            this.getDicts('fund_disclosure_object').then(response => {
                this.disclosureObjectOptions = response.data
            })
            this.getDicts('fund_disclosure_type').then(response => {
                this.disclosureTypeOptions = response.data
            })
            this.getDicts('fund_disclosure_quarter').then(response => {
                this.reportPeriodSeasonOptions = response.data
            })
            this.getDicts('fund_report_type').then(response => {
              this.reportTypeOptions = response.data
            })
            this.getDicts('sys_yes_no').then(response => {
              this.handleOptions = response.data
              this.isSealOptions = response.data
            })
            this.getDicts('seal_type').then(response => {
              this.sealTypeDict = response.data
            })
            this.$bus.$emit('async_done')
        },
        methods: {
            // 初始化数据
            init(data) {
                this.loading = true
                if (data != null && data.id !== undefined) {
                    getFundDisclosure(data.id).then(response => {
                        this.form = response.data
                        this.loading = false
                    })
                } else {
                    this.reset()
                    this.loading = false
                }
            },
            // 表单重置
            reset() {
                this.form = {
                id: undefined,
                isSeal: 'N',
                disclosureObject: undefined,
                disclosureType: undefined,
                reportPeriodYear: undefined,
                reportPeriodSeason: undefined,
                remark: undefined,
                fileList: [],
                createBy: undefined,
                createTime: undefined,
                updateBy: undefined,
                updateTime: undefined,
                delFlag: undefined,
                actId: undefined,
                actStatus: undefined,
                fundId: this.$route.query.id,
                reportType: undefined
                }
                this.resetForm('form')
            },
            // 取消按钮
            cancel() {
                this.$parent.$parent.formOpen = false
                this.$parent.$parent.reset()
            },
            // 关闭form页面
            closeForm() {
              // 关闭form页面遮罩层
              this.loading = false
              // 关闭form页面
              if (this.$parent.$parent.formOpen !== undefined) {
                this.$parent.$parent.formOpen = false
              }
              // 刷新list页面
              if (this.$parent.$parent.getList !== undefined) {
                this.$parent.$parent.getList()
              }
            },
            /** 提交按钮 */
            submitForm: function(type) {
              return new Promise((resolve, reject) => {
                this.$refs['form'].validate(valid => {
                  var submitFlag = true
                  if ((this.form.fileList === undefined || this.form.fileList === null || this.form.fileList.length <= 0) && valid) {
                    submitFlag = false
                    this.$alert(this.$t('请添加' + (this.form.reportType !== 'XXPL' ? '管理报告相关文件!' : '要披露的文件!')), this.$t('提示'), {
                      confirmButtonText: this.$t('关闭'),
                      type: 'warning'
                    })
                  }
                  // 验证数据
                  if (valid && submitFlag) {
                    // 弹出遮罩层
                    this.loading = true
                    // 保存数据
                    saveFundDisclosure(this.form).then(response => {
                      if (response.code === 200) {
                        // 点击的按钮是保存并启动流程
                        if (type === 'process') {
                          // 设置数据id方式启动流程后取消并再次启动会创建多条记录
                          this.form.id = response.data.id
                          // 启动流程
                          this.startProcess(response.data)
                          // 点击的仅保存
                        } else {
                          this.msgSuccess(this.$t('保存成功'))
                          // 关闭form页面
                          this.closeForm()
                        }
                        resolve()
                      } else {
                        this.msgError(response.msg)
                        this.loading = false
                        reject()
                      }
                    }).catch(() => {
                      this.loading = false
                    })
                  } else {
                    this.locationError(document)
                  }
                })
              })
           },
            // 启动流程
           startProcess: async function(data) {
               var fundName = await getFundName(this.$route.query.id)
               this.loading = false
               // 启动流程时候传入的参数
               const processData = {}
               // 待办标题
               processData.title = '「' + fundName + '」' + ': ' + this.form.actTitle + '(' + this.reportTypeFormat(data.reportType) + ')'
               // 业务表名
               processData.dataTable = 'fund_disclosure'
               // 业务ID
               processData.dataId = data.id
               // 业务表单地址(待办页面需要打开的页面)
               processData.formPath = '@/views/fund/disclosure/fundDisclosureForm'
               processData.viewPath = '@/views/fund/disclosure/fundDisclosureView'
               // 菜单标识(根据菜单标识判断的走哪个流程)
               processData.menuKey = this.menuKey
               this.startProcessByMenu(processData, () => {
                   this.form.actStatus = 'D'
                   this.msgSuccess(this.$t('数据保存成功,流程启动成功'))
                   this.closeForm()
               })
           },
          // 披露类型字典翻译
          disclosureTypeFormat(disclosureType) {
            return this.selectDictLabel(this.disclosureTypeOptions, disclosureType)
          },
          // 报告类型字典翻译
          reportTypeFormat(reportType) {
            return this.selectDictLabel(this.reportTypeOptions, reportType)
          },
          // 用印明细
          addPayment() {
            const row = {
              id: undefined,
              investMainType: '',
              investMain: '',
              sealType: '',
              remark: ''
            }
            if (!(this.form.oaSealDetailList instanceof Array)) {
              this.$set(this.form, 'oaSealDetailList', [])
            }
            this.$nextTick(() => {
              this.form.oaSealDetailList.push(row)
            })
          },
          // 删除用印明细
          delHandle(index, row) {
            const id = row.id
            if (id !== undefined && id !== '' && id != null) {
              this.$confirm(this.$t('是否确认删除?'), this.$t('警告'), {
                confirmButtonText: this.$t('确定'),
                cancelButtonText: this.$t('取消'),
                type: 'warning'
              })
                .then(function() {
                  return deleteOaSealDetail(id)
                }).then(() => {
                this.form.oaSealDetailList.splice(index, 1)
                return this.msgSuccess(this.$t('删除成功'))
              })
                .catch(function() {})
            } else {
              this.form.oaSealDetailList.splice(index, 1)
            }
          },
          // 用印主体校验重复
          duplicateVerificationSubject(val) {
            this.$nextTick(() => {
              if (this.form.oaSealDetailList !== undefined && this.form.oaSealDetailList !== null) {
                var count = 0
                this.form.oaSealDetailList.some((item, index) => {
                  if (item.investMain === val) {
                    if (count > 0) {
                      this.form.oaSealDetailList.splice(index, 1)
                      this.msgError(this.$t('该主体已存在'))
                      return true
                    }
                    count++
                  }
                })
              }
            })
          }

        }

    }
</script>
